import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';
import 'package:jet_rails/jr_utils/jr_toast.dart';
import 'package:permission_handler/permission_handler.dart';

class JrMedia {
  String pageName = "example.MediaUtil";

  factory JrMedia() => _getInstance();

  static JrMedia get instance => _getInstance();
  static JrMedia? _instance;

  JrMedia._internal();

  static JrMedia _getInstance() {
    _instance ??= JrMedia._internal();
    return _instance!;
  }

  Future<String?> takePhoto() async {
    PermissionStatus status = await Permission.camera.request();
    if (status != PermissionStatus.granted) {
      JrToast.show("Grant permissions to the camera first");
      return null;
    }

    XFile? imgfile = await ImagePicker().pickImage(source: ImageSource.camera);
    if (imgfile == null) {
      return null;
    }
    String imgPath = imgfile.path;
    if (TargetPlatform.android == defaultTargetPlatform) {
      imgPath = "file://${imgfile.path}";
    }
    return imgPath;
  }

  Future<String?> pickImage() async {
    PermissionStatus status = await Permission.photos.request();
    if (status != PermissionStatus.granted) {
      JrToast.show("Grant permissions to the photos first");
      return null;
    }

    XFile? imgfile = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (imgfile == null) {
      return null;
    }
    String imgPath = imgfile.path;
    if (TargetPlatform.android == defaultTargetPlatform) {
      imgPath = "file://${imgfile.path}";
    }
    return imgPath;
  }

  Future<List<File>> pickFiles() async {
    PermissionStatus status = await Permission.storage.request();
    if (status != PermissionStatus.granted) {
      JrToast.show("Grant permissions to the storage first");
      return [];
    }

    FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);
    List<File> files = [];
    if (result != null) {
      files = result.paths.map((path) => File(path!)).toList();
    }
    return files;
  }
}
